package org.codeanalyzer.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Represents Java Class
 */
public class ApiClass extends ApiItem
{
    private final Map<String, ApiMethod> methods = new HashMap<String, ApiMethod>();
    private final String simpleName;

    /**
     * Constructs ApiClass
     * 
     * @param apiPackage
     *            the package containing the class
     * @param simpleName
     *            the class name without packages
     */
    public ApiClass(ApiPackage apiPackage, String simpleName)
    {
        super(generateName(apiPackage.getName(), simpleName));
        this.simpleName = simpleName;
    }

    public static String generateName(String packageName, String className)
    {
        return packageName + "." + className;
    }

    public static String generateKey(String className)
    {
        return className;
    }

    public ApiMethod addMethod(String methodName, String modifiers, String returnType, String parameters)
    {
        ApiMethod apiMethod;
        String methodKey = ApiMethod.generateKey(methodName, parameters);
        if (methods.containsKey(methodKey))
            apiMethod = methods.get(methodKey);
        else
        {
            apiMethod = new ApiMethod(this, methodName, modifiers, returnType, parameters);
            methods.put(methodKey, apiMethod);
        }

        return apiMethod;
    }

    public String getSimpleName()
    {
        return simpleName;
    }

    public List<ApiMethod> getMethods()
    {
        List<ApiMethod> classList = new ArrayList<ApiMethod>(methods.values());
        Collections.sort(classList);
        return classList;
    }

    public Map<String, ApiMethod> getMethodMap()
    {
        return Collections.unmodifiableMap(methods);
    }


    public int getTotalMethods()
    {
        return methods.size();
    }

    public int getTotalCoveredMethods()
    {
        int totalCovered = 0;
        for(ApiMethod apiMethod : methods.values())
            totalCovered += apiMethod.isCovered() ? 1 : 0;
        return totalCovered;
    }

    public boolean isCovered()
    {
        return getTotalCoveredMethods() > 0;
    }

    public int getMethodCoverage()
    {
        return (int)((double)getTotalCoveredMethods() / (double)getTotalMethods() * 100.0);
    }

}
